package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author houChen
 * @date 2022/2/27 21:29
 * @Description:
 */
@Configuration
public class MyRabbitConfig {

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 只有当消费者监听某个队列的时候，
     * 才会去创建容器中注入的 交换机，队列 绑定关系
     */
   /* @RabbitListener(queues = "stock.release.stock.queue")
    public void handler(Message message){

    }*/
    
    /**
     * 创建库存相关的交换机 队列 和绑定关系
     */
    @Bean
    public Exchange stockEventExchange(){
        //public TopicExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments)
        return new TopicExchange("stock-event-exchange", true, false);
    }

    @Bean
    public Queue stockReleaseStockQueue(){
        //public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        //exclusive: 队列是否是排他的（队列是否只有一个消费者）
        return new Queue("stock.release.stock.queue", true, false, false, null);
    }


    @Bean
    public Queue stockDelayQueue(){
        //public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        //exclusive: 队列是否是排他的（队列是否只有一个消费者）
        //设置死信队列的属性
        //x-dead-letter-exchange: order-event-exchange
        //x-dead-letter-routing-key: order.release.order
        //x-message-ttl: 120000  //注意：库存延时队列的时间一定要大于 订单延时队列的时间，因为库存是否解锁需要根据订单的状态来进行判断
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange","stock-event-exchange");
        args.put("x-dead-letter-routing-key","stock.release");
        args.put("x-message-ttl",120000);
        return new Queue("stock.delay.queue", true, false, false, args);
    }


    @Bean
    public Binding stockReleaseBinding(){
        //public Binding(String destination, Binding.DestinationType destinationType, String exchange, String routingKey, Map<String, Object> arguments)
        Binding binding = new Binding("stock.release.stock.queue",Binding.DestinationType.QUEUE,
                "stock-event-exchange","stock.release.#",null);
        return binding;
    }

    @Bean
    public Binding stockDelayBinding(){
        //public Binding(String destination, Binding.DestinationType destinationType, String exchange, String routingKey, Map<String, Object> arguments)
        Binding binding = new Binding("stock.delay.queue",Binding.DestinationType.QUEUE,
                "stock-event-exchange","stock.locked",null);
        return binding;
    }

}